<template>
    <div id="app">
      <header>
        <h1>2024待办事项</h1>
        <form id="new-task-form">
          <input
            type="text"
            v-model="task"
            id="new-task-input"
            placeholder="把计划写下来吧?"
          />
          <input
            type="submit"
            id="new-task-submit"
            placeholder="Add Task"
            @click.prevent="handleAdd"
          />
        </form>
      </header>
      <main>
        <section class="task-list">
          <h2>任务列表</h2>
          <div id="tasks">
            <template v-for="(item, index) in tasks" :key="index">
              <div class="task">
                <div class="content">
                  <input
                    type="text"
                    class="text"
                    v-model="task[index]"
                    :disabled="readonly[index]"
                  />
                </div>
                <div class="actions">
                  <button
                    class="edit"
                    @click="handleEdit($event, item, index)"
                  >
                    {{ btnName[index] }}
                  </button>
                  <button class="delete" @click="handleDelete(index)">
                    Delete
                  </button>
                </div>
              </div>
            </template>
          </div>
        </section>
      </main>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  
  // 定义响应式数据
  const tasks = ref([]);
  const task = ref('');
  const btnName = ref([]);
  const readonly = ref([]);
  
  // 定义添加任务的方法
  const handleAdd = () => {
    if (task.value) {
      tasks.value.push(task.value);
      task.value = '';
      btnName.value.push('编辑');
      readonly.value.push(true);
    }
  };
  
  // 定义删除任务的方法
  const handleDelete = (index) => {
    tasks.value.splice(index, 1);
  };
  
  // 定义编辑任务的方法
  const handleEdit = ($event, item, index) => {
    console.log($event, item, index);
  
    if (btnName.value[index] === '编辑') {
      btnName.value[index] = '保存';
      readonly.value[index] =!readonly.value[index];
    } else {
      tasks.value[index] = item;
      btnName.value[index] = '编辑';
      readonly.value[index] =!readonly.value[index];
      return;
    }
  };
  </script>
  
  <style>
  /* 这里可以添加组件相关的样式，如果有需要从原来的tasklist.css中提取过来的样式，可以在这里补充 */
  </style>